<template>
  <div class="permissions-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">权限管理</h1>
        <p class="page-description">查看和管理系统权限配置</p>
      </div>
      <div class="header-actions">
        <button @click="refreshData" class="btn btn-outline">
          <el-icon><Refresh /></el-icon>
          刷新
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon bg-blue">
          <el-icon><Grid /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalModules }}</div>
          <div class="stat-label">权限模块</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon bg-green">
          <el-icon><Key /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalPermissions }}</div>
          <div class="stat-label">权限总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon bg-orange">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalRoles }}</div>
          <div class="stat-label">角色总数</div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <div class="search-box">
        <el-icon><Search /></el-icon>
        <input 
          v-model="searchQuery"
          type="text" 
          placeholder="搜索权限模块或权限名称..."
          class="search-input"
        />
      </div>
      <div class="filters">
        <select v-model="levelFilter" class="filter-select">
          <option value="">全部级别</option>
          <option value="view">查看</option>
          <option value="edit">编辑</option>
          <option value="manage">管理</option>
        </select>
      </div>
    </div>

    <!-- 初始加载状态 -->
    <PageLoading 
      v-if="initialLoading"
      :title="isRefreshing ? '正在刷新权限数据' : '正在加载权限数据'"
      :subtitle="isRefreshing ? '请稍候，正在更新数据...' : '请稍候，正在为您准备数据...'"
    />
    
    <!-- 权限模块列表 -->
    <div v-else class="permissions-container">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="filteredModules.length === 0" class="empty-state">
        <div class="empty-icon">
          <el-icon><Key /></el-icon>
        </div>
        <h3>暂无权限数据</h3>
        <p>{{ searchQuery ? '没有找到匹配的权限' : '系统暂无权限配置' }}</p>
      </div>

      <div v-else class="modules-list">
        <div 
          v-for="module in filteredModules" 
          :key="module.code" 
          class="module-card"
        >
          <div class="module-header" @click="toggleModule(module.code)">
            <div class="module-info">
              <h3 class="module-name">{{ module.name }}</h3>
              <p class="module-description">{{ module.description || '暂无描述' }}</p>
              <div class="module-meta">
                <span class="module-code">{{ module.code }}</span>
                <span class="permission-count">{{ module.permissions.length }} 个权限</span>
              </div>
            </div>
            <div class="module-toggle">
              <el-icon>
                <component :is="expandedModules.includes(module.code) ? 'ArrowUp' : 'ArrowDown'" />
              </el-icon>
            </div>
          </div>
          
          <div v-if="expandedModules.includes(module.code)" class="module-content">
            <div class="permissions-grid">
              <div 
                v-for="permission in module.permissions" 
                :key="permission.code"
                class="permission-item"
              >
                <div class="permission-header">
                  <div class="permission-info">
                    <h4 class="permission-name">{{ permission.name }}</h4>
                    <code class="permission-code">{{ permission.code }}</code>
                  </div>
                  <span :class="['permission-level', `level-${permission.level}`]">
                    {{ getLevelName(permission.level) }}
                  </span>
                </div>
                <p class="permission-description">{{ permission.description || '暂无描述' }}</p>
                <div class="permission-roles">
                  <span class="roles-label">拥有此权限的角色：</span>
                  <div class="roles-tags">
                    <span 
                      v-for="role in getRolesWithPermission(permission.code)" 
                      :key="role.code"
                      class="role-tag"
                    >
                      {{ role.name }}
                    </span>
                    <span v-if="getRolesWithPermission(permission.code).length === 0" class="no-roles">
                      暂无角色
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 权限检查工具 -->
    <div class="permission-checker">
      <div class="checker-header">
        <h3>权限检查工具</h3>
        <p>检查特定权限的配置情况</p>
      </div>
      <div class="checker-form">
        <div class="form-group">
          <label>权限代码</label>
          <input 
            v-model="permissionChecker.code"
            type="text" 
            placeholder="输入权限代码，如：user:view"
            class="form-input"
          />
        </div>
        <button @click="checkPermission" class="btn btn-primary">
          <el-icon><Search /></el-icon>
          检查权限
        </button>
      </div>
      <div v-if="permissionChecker.result" class="checker-result">
        <div class="result-header">
          <h4>检查结果</h4>
          <span :class="['result-status', permissionChecker.result.exists ? 'exists' : 'not-exists']">
            {{ permissionChecker.result.exists ? '权限存在' : '权限不存在' }}
          </span>
        </div>
        <div v-if="permissionChecker.result.exists" class="result-details">
          <div class="detail-item">
            <label>权限名称</label>
            <span>{{ permissionChecker.result.name }}</span>
          </div>
          <div class="detail-item">
            <label>所属模块</label>
            <span>{{ permissionChecker.result.module }}</span>
          </div>
          <div class="detail-item">
            <label>权限级别</label>
            <span :class="['permission-level', `level-${permissionChecker.result.level}`]">
              {{ getLevelName(permissionChecker.result.level) }}
            </span>
          </div>
          <div class="detail-item">
            <label>拥有角色</label>
            <div class="roles-tags">
              <span 
                v-for="role in permissionChecker.result.roles" 
                :key="role.code"
                class="role-tag"
              >
                {{ role.name }}
              </span>
              <span v-if="permissionChecker.result.roles.length === 0" class="no-roles">
                暂无角色
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Grid, 
  Key, 
  UserFilled, 
  Search
} from '@element-plus/icons-vue'
import PageLoading from '@/components/ui/PageLoading.vue'

// 类型定义
interface Permission {
  code: string
  name: string
  description?: string
  level: string
}

interface PermissionModule {
  code: string
  name: string
  description?: string
  permissions: Permission[]
}

interface Role {
  code: string
  name: string
  permissions: string[]
}

// 响应式数据
const userStore = useUserStore()
const loading = ref(false)
const initialLoading = ref(true)
const isRefreshing = ref(false)
const permissionModules = ref<PermissionModule[]>([])
const roles = ref<Role[]>([])
const expandedModules = ref<string[]>([])

// 搜索和筛选
const searchQuery = ref('')
const levelFilter = ref('')

// 权限检查器
const permissionChecker = ref({
  code: '',
  result: null as any
})

// 计算属性
const totalModules = computed(() => permissionModules.value.length)

const totalPermissions = computed(() => {
  return permissionModules.value.reduce((total, module) => total + module.permissions.length, 0)
})

const totalRoles = computed(() => roles.value.length)

const filteredModules = computed(() => {
  let filtered = permissionModules.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.map(module => ({
      ...module,
      permissions: module.permissions.filter(permission =>
        permission.name.toLowerCase().includes(query) ||
        permission.code.toLowerCase().includes(query) ||
        module.name.toLowerCase().includes(query)
      )
    })).filter(module => module.permissions.length > 0)
  }

  // 级别过滤
  if (levelFilter.value) {
    filtered = filtered.map(module => ({
      ...module,
      permissions: module.permissions.filter(permission => permission.level === levelFilter.value)
    })).filter(module => module.permissions.length > 0)
  }

  return filtered
})

// 方法
const loadPermissionModules = async () => {
  try {
    loading.value = true
    
    // 使用统一的API调用方式
    const { getPermissionModules } = await import('@/api/users')
    const response = await getPermissionModules()
    
    // 处理统一响应格式
    if (response.data && response.data.success) {
      const moduleData = response.data.data
      permissionModules.value = Array.isArray(moduleData) ? moduleData : []
      
      // 默认展开第一个模块
      if (permissionModules.value.length > 0) {
        expandedModules.value = [permissionModules.value[0].code]
      }
    } else {
      ElMessage.error(response.data?.message || '加载权限模块失败')
    }
  } catch (error) {
    console.error('Load permission modules error:', error)
    ElMessage.error('加载权限模块失败')
  } finally {
    loading.value = false
  }
}

const loadRoles = async () => {
  try {
    const response = await fetch('/api/v1/roles/', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      // 处理统一响应格式
      if (result.success && result.data) {
        // 确保result.data是数组，如果不是则使用空数组
        const validRolesData = Array.isArray(result.data) ? result.data : []
        roles.value = validRolesData.map((role: any) => ({
          code: role.code,
          name: role.name,
          permissions: role.permissions || []
        }))
      } else {
        roles.value = []
        ElMessage.error(result.message || '加载角色列表失败')
      }
    } else {
      // API调用失败时，确保roles.value是空数组
      roles.value = []
      if (response.status === 401) {
        ElMessage.warning('请先登录后再访问权限管理')
      } else {
        ElMessage.error('加载角色列表失败')
      }
    }
  } catch (error) {
    console.error('Load roles error:', error)
    // 发生错误时，确保roles.value是空数组
    roles.value = []
    ElMessage.error('加载角色列表失败')
  }
}

const refreshData = async () => {
  try {
    isRefreshing.value = true
    initialLoading.value = true
    await Promise.all([
      loadPermissionModules(),
      loadRoles()
    ])
    ElMessage.success('权限数据已刷新')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请稍后重试')
  } finally {
    setTimeout(() => {
      initialLoading.value = false
      isRefreshing.value = false
    }, 300)
  }
}

const toggleModule = (moduleCode: string) => {
  const index = expandedModules.value.indexOf(moduleCode)
  if (index > -1) {
    expandedModules.value.splice(index, 1)
  } else {
    expandedModules.value.push(moduleCode)
  }
}

const getLevelName = (level: string) => {
  const levelMap: Record<string, string> = {
    'view': '查看',
    'edit': '编辑',
    'manage': '管理'
  }
  return levelMap[level] || level
}

const getRolesWithPermission = (permissionCode: string) => {
  return roles.value.filter(role => {
    if (!role.permissions) return false
    // 管理员拥有所有权限
    if (role.permissions.includes('*')) return true
    return role.permissions.includes(permissionCode)
  })
}

const checkPermission = () => {
  if (!permissionChecker.value.code) {
    ElMessage.warning('请输入权限代码')
    return
  }

  // 查找权限
  let foundPermission = null
  let foundModule = null

  for (const module of permissionModules.value) {
    const permission = module.permissions.find(p => p.code === permissionChecker.value.code)
    if (permission) {
      foundPermission = permission
      foundModule = module
      break
    }
  }

  if (foundPermission && foundModule) {
    const rolesWithPermission = getRolesWithPermission(permissionChecker.value.code)
    permissionChecker.value.result = {
      exists: true,
      name: foundPermission.name,
      module: foundModule.name,
      level: foundPermission.level,
      roles: rolesWithPermission
    }
  } else {
    permissionChecker.value.result = {
      exists: false
    }
  }
}

// 生命周期
onMounted(async () => {
  await Promise.all([
    loadPermissionModules(),
    loadRoles()
  ])
  initialLoading.value = false
})
</script>

<style scoped>
.permissions-management {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid transparent;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.btn-outline {
  background: white;
  color: #374151;
  border-color: #d1d5db;
}

.btn-outline:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-icon.bg-blue { background: #3b82f6; }
.stat-icon.bg-green { background: #10b981; }
.stat-icon.bg-orange { background: #f59e0b; }

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.search-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.search-box .el-icon {
  position: absolute;
  left: 12px;
  color: #9ca3af;
  z-index: 1;
}

.search-input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.filters {
  display: flex;
  gap: 12px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.permissions-container {
  margin-bottom: 32px;
}

.loading-state, .empty-state {
  background: white;
  padding: 60px 20px;
  text-align: center;
  color: #6b7280;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f4f6;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  color: #d1d5db;
  margin-bottom: 16px;
}

.modules-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.module-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.module-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  cursor: pointer;
  transition: background-color 0.2s;
}

.module-header:hover {
  background: #f9fafb;
}

.module-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.module-description {
  margin: 0 0 12px 0;
  color: #6b7280;
  font-size: 14px;
}

.module-meta {
  display: flex;
  gap: 16px;
  align-items: center;
}

.module-code {
  background: #f3f4f6;
  color: #374151;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.permission-count {
  color: #6b7280;
  font-size: 12px;
}

.module-toggle {
  color: #6b7280;
  font-size: 16px;
}

.module-content {
  padding: 24px;
  background: #f9fafb;
}

.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.permission-item {
  background: white;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.permission-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.permission-code {
  background: #f3f4f6;
  color: #6b7280;
  padding: 1px 4px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 11px;
}

.permission-level {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.permission-level.level-view {
  background: #dbeafe;
  color: #1d4ed8;
}

.permission-level.level-edit {
  background: #fef3c7;
  color: #d97706;
}

.permission-level.level-manage {
  background: #fee2e2;
  color: #dc2626;
}

.permission-description {
  color: #6b7280;
  font-size: 13px;
  margin-bottom: 12px;
  line-height: 1.4;
}

.permission-roles {
  border-top: 1px solid #f3f4f6;
  padding-top: 12px;
}

.roles-label {
  display: block;
  font-size: 12px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.roles-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.role-tag {
  background: #e0e7ff;
  color: #3730a3;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.no-roles {
  color: #9ca3af;
  font-size: 11px;
  font-style: italic;
}

.permission-checker {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.checker-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
}

.checker-header h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.checker-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.checker-form {
  padding: 24px;
  display: flex;
  gap: 16px;
  align-items: end;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.form-input {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.checker-result {
  padding: 24px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.result-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.result-status.exists {
  background: #dcfce7;
  color: #166534;
}

.result-status.not-exists {
  background: #fee2e2;
  color: #dc2626;
}

.result-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-item label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  min-width: 80px;
}

.detail-item span {
  font-size: 14px;
  color: #6b7280;
}

@media (max-width: 768px) {
  .checker-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .permissions-grid {
    grid-template-columns: 1fr;
  }
  
  .search-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filters {
    justify-content: stretch;
  }
  
  .filter-select {
    flex: 1;
  }
}
</style>